package com.summer.core.listener;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Repository;

import com.cxl.price.top.service.TopBaseService;
import com.summer.core.util.SysPath;
import com.summer.core.util.XmlHelper;
import com.taobao.api.TaobaoRequest;

/**
 * 容器初始化监听器，从数据库加载相关数据
 * @author wwwlike
 *
 */
@Repository
public class MyContextListener   implements ApplicationListener {
	private final static String xmlfile=SysPath.getRealPath("default_request.xml");
	
	public void onApplicationEvent(ApplicationEvent event) {
		try {
			initDefaultRequestObj();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	private <T extends TaobaoRequest> void initDefaultRequestObj() throws Exception
	{
		
		 	Map map=new HashMap<Object,TaobaoRequest>();
		try {
			  Document doc = XmlHelper.parseXml(xmlfile);
			  Element root=doc.getRootElement();
//			  Iterator it = root.elementIterator();
//			  Element element = (Element) it.next();
			 
			   for(Iterator iterator = root.elementIterator("request");iterator.hasNext();){  
                   Element request = (Element) iterator.next();  
              
                   Iterator it = request.elementIterator();
                   T tobj=null;
                   while(it.hasNext()){
                
                	   Element detail = (Element) it.next();  
                	  if(detail.getName().equals("class")){
                		  tobj= (T) Class.forName(detail.getTextTrim()).newInstance();
                		//  System.out.println("class");
                	  }else if(detail.getName().equals("attr")){
                		  if(tobj!=null){
                			  Iterator attr = detail.elementIterator();
                			  while(attr.hasNext()){
                				  Element attribute = (Element) attr.next();
                				  Class clazz=getFieldClass(attribute.attribute("fieldType")==null?null:attribute.attribute("fieldType").getText());
                				  
                				  Method setMethod=tobj.getClass().getMethod(attribute.getName(),clazz);
      							  setMethod.invoke(tobj, getFieldValue(clazz,attribute.getTextTrim()));
                			  }
                		  }
                	  }else if(detail.getName().equals("dynamicAttr")){
                		  if(tobj!=null){
                			  String text=detail.getTextTrim();
            				  List list=null;
            				  if(map.get(tobj.getClass().getName()+"_dynamicAttr")==null){
                    			   list=new ArrayList();
                    		  }else{
                    			   list=(List)map.get(tobj.getClass().getName()+"_dynamicAttr");
                    		  }
            				  list.add(text);
            				  map.put(tobj.getClass().getName()+"_dynamicAttr",list);
            			  }
                	  }
                   }
                   map.put((Class<T>) tobj.getClass(), tobj);
                
               }  
		}catch (DocumentException e) {
			e.printStackTrace();
		}
		
		TopBaseService.map=map;
	}
	
	public Class getFieldClass(String fieldType){
		if(fieldType==null){
			return String.class;
		}else if(fieldType.equals("LONG")){
			return Long.class;
		}else{
			return String .class;
		}
	}
	
	public Object getFieldValue(Class clazz,String value){
		if(clazz==null){
			return value;
		}else if(clazz==Long.class){
			return new Long(value);
		}else{
			return value;
		}
	}
	
	
	public void read(Element e) {
        if (e.nodeCount() > 0) {
            Iterator<?> it = e.elementIterator();
            while (it.hasNext()) {
                Element ele = (Element) it.next();
                read(ele);
                System.out.println("Element :" + ele.getName() + " Path "
                        + ele.getUniquePath());

                if (ele.attributeCount() > 0) {
                    Iterator<?> ait = ele.attributeIterator();
                    System.out.print("  Data : [ ");
                    while (ait.hasNext()) {
                        Attribute attribute = (Attribute) ait.next();
                        System.out.print(attribute.getName() + " : "
                                + attribute.getData() + "   ");
                    }
                    System.out.print(" ]");
                    System.out.println();
                }
            }
        }

    }

    
	
	public static void main(String[] args) {
		try {
			new MyContextListener().initDefaultRequestObj();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
